package org.apache.solr.formula;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.solr.search.SolrIndexSearcher;

import cn.ac.cintcm.prespring.util.StringUtil;

public class ElementsIndex {
    
    private SolrIndexSearcher searcher;
    private HashMap<String, HashMap<Integer,String>> indexedElements;
    private List<String> indexes;
    private String id;

    public ElementsIndex(SolrIndexSearcher searcher, String idName, List<String> indexs) {
        this.searcher = searcher;
        this.indexes = indexs;
        this.id = idName;
        init();
    }
    
    public HashMap<Integer, List<Integer>> 
        getIndex(String index) throws IOException {
        HashMap<Integer, List<Integer>> cids = new HashMap<Integer, List<Integer>>();
        HashMap<Integer,String> hm = indexedElements.get(index);
        for (Integer i : hm.keySet()) {
            List<Integer> ids = StringUtil.string2List(hm.get(i));
            if (ids != null) {
                cids.put(i, ids);
            }
        }
        return cids;
    }
    
    protected void init() {
        indexedElements = new HashMap<String, HashMap<Integer,String>>();
        for (String index : indexes) {
            indexedElements.put(index, new HashMap<Integer,String>());
        }
        IndexReader ir = searcher.getReader();
        int count = ir.maxDoc();
        for (int i=0; i < count; i++) {
            Document doc;
            try {
                doc = ir.document(i);
                for (String index : indexes) {
                    String ids = doc.get(id);
                    String names = doc.get(index);
                    indexedElements.get(index).put(Integer.valueOf(ids), names);
                }
            } catch (CorruptIndexException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public HashMap<Integer, String> getIndexName(
            String indexedName) throws IOException {

        return indexedElements.get(indexedName);
    }
}
